//
//  Y2StateMachine.m
//  Y2EventBus
//
//  Created by harry.tong on 2021/6/18.
//

#import "Y2StateMachine.h"
#import "Y2Router.h"

@interface Y2StateMachine()<NSCopying,NSMutableCopying>

@property (nonatomic, assign) int status;

@end

static Y2StateMachine *instance = nil;


@implementation Y2StateMachine

+ (instancetype)shareManager{
    static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            instance = [[self alloc] init];
            instance.status = 100;
        });
        return instance;
}

+ (id)allocWithZone:(struct _NSZone *)zone{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [super allocWithZone:zone];
        instance.status = 100;
    });
    return instance;
}

- (id)copyWithZone:(nullable NSZone *)zone{
    return instance;
}

- (id)mutableCopyWithZone:(nullable NSZone *)zone{
    return instance;
}


/// 获取当前状态
+(int) currentStatus{
    return [Y2StateMachine shareManager].status;
}

/// 状态变更
+(void) moduleStatusTransition:(int)status{
    [Y2StateMachine moduleStatusTransition:status info:nil];
}

+(void) moduleStatusTransition:(int)status info:(id)obj{
    Y2StateMachine *manager = [Y2StateMachine shareManager];
    manager.status = status;
    
    if (status >= 100 && status < 200){ // Init
        Y2ModuleInitStatus moduleStatus = status;
        switch (moduleStatus) {
            case ModuleInitSuccessStatus: manager.status = ModuleInitStandByStatus; break;
            case ModuleInitFailStatus: manager.status = ModulUnInitStatus; break;;
            default:break;
        }
    }else if (status >= 200 && status < 300){ // login
        Y2ModuleLoginStatus moduleStatus = status;
        switch (moduleStatus) {
            default:break;
        }
    }else{ // pay
        Y2ModulePayStatus moduleStatus = status;
        switch (moduleStatus) {
            default:break;
        }
    }
    if (status != manager.status){
        [Y2StateMachine transition:@{@"status":@(status), @"info":(obj ?: @"")}];
    }
    [Y2StateMachine transition:@{@"status":@(manager.status), @"info":(obj ?: @"")}];
}


+(void) transition:(NSDictionary *)dict{
    [Y2Router callWithProtocol:@"Y2EventBusProtocol" moduleType:@"Y2Router" method:@"StateMachineTransition" args:dict];
}



@end
